import React, { useState, useEffect } from 'react';
import { Input, Button, List } from 'antd';
import '../style/Todolist.css';
import { getAllTasks, addTask, deleteTask, updateTask, deleteAllTasks } from '../api/tasks-api';
import { DeleteOutlined, EditOutlined } from '@ant-design/icons';
import { useAuth } from '../context/AuthProvider';

const Todolist = () => {
  const [inputValue, setInputValue] = useState('');
  const [todos, setTodos] = useState([]);
  const [editingId, setEditingId] = useState(null);
  const [editingText, setEditingText] = useState('');
  const {user,logout}=useAuth()

  useEffect(() => {
    fetchTasks();
  }, []);

  const fetchTasks = async () => {
    try{
      const response = await getAllTasks(user.id);
      const {data}=response.data;
      setTodos(data);
    }catch(err){
      console.log(err);
    }
  };

  // 添加任务
  const handleAdd = async () => {
    if(inputValue){
      try{
        let packData={
            text:inputValue,
            user_id:user.id
        }
        const response = await addTask(packData);
        let res=response.data;
        if(res.status===1){
          await fetchTasks();
          setInputValue('');
        }
      }catch(err){
        console.log(err);
      }
    }
  };

  // 删除所有任务
  const handleDeleteAll = async () => {
    try{
      const response=await deleteAllTasks(user.id);
      let res=response.data;
      if(res.status===1){
        await fetchTasks();
      }
    }catch(err){
      console.log(err);
    }
  };

  // 删除单个任务
  const handleDelete = async (id) => {
    try{
      const response=await deleteTask(id);
      let res=response.data;
      if(res.status===1){
        await fetchTasks();
      }
    }catch(err){
      console.log(err);
    }
  };

  // 开始编辑
  const handleEdit = (todo) => {
    setEditingId(todo.id);
    setEditingText(todo.text);
  };

  // 保存编辑
  const handleSave = async (id) => {
    if (editingText.trim()) {
      try{
        const response=await updateTask(editingText,id);
        let res=response.data;
        if(res.status===1){
          await fetchTasks();
          setEditingId(null);
        }
      }catch(err){
        console.log(err);
      }
    }
  };

  return (
    <div className="todo-container">
      <div style={{ 
      display: 'flex', 
      alignItems: 'center',
      gap: '20px',  // 添加固定间距
      marginBottom: '20px'
    }}>
      <h1 style={{ margin: 0 }}>TODO List</h1>  {/* 移除 h1 的默认边距 */}
      <Button 
        onClick={logout}
        style={{
          backgroundColor: '#ff4d4f',
          color: '#fff',
          borderRadius: '4px'
        }}
      >
        退出登录
      </Button>
    </div>
      
      <div className="input-group">
        <Input 
          value={inputValue}
          onChange={(e) => setInputValue(e.target.value)}
          onPressEnter={handleAdd}
          placeholder="请输入待办事项内容"
        />
        <div className="button-group">
          <Button onClick={handleAdd}
          style={{
            backgroundColor:'#07C160',color:'#fff',
            width:'80px'
          }}>
            添加
            </Button>

          <Button onClick={handleDeleteAll} color="danger" variant="solid"
          style={{
            width:'80px'
          }}>
            删除全部
            </Button>
        </div>
      </div>

      <List
        className="todo-list"
        dataSource={todos}
        renderItem={todo => (
          <List.Item key={todo.id} className="list-item">
            {editingId === todo.id ? (
              <div className="item-content">
                <Input 
                  value={editingText}
                  onChange={(e) => setEditingText(e.target.value)}
                  onPressEnter={() => handleSave(todo.id)}
                />

                <Button size="small" onClick={() => handleSave(todo.id)}
                style={{
                  backgroundColor:'#07C160',
                  color:'#fff',
                  width:'80px'
                }}>
                  保存
                </Button>

              </div>
            ) : (
              <div className="list-item-container">
                <div className="list-item-left">
                  <span className="dot" style={{fontSize:'35px'}}>•</span>
                  <span className="todo-text" style={{fontSize:'22px'}}>{todo.text}</span>
                </div>
                <div className="todo-actions">
                  <Button icon={<EditOutlined />} onClick={() => handleEdit(todo)}/>
                  <Button icon={<DeleteOutlined />} onClick={() => handleDelete(todo.id)}/>
                </div>
              </div>
            )}
          </List.Item>
        )}
      />
    </div>
  );
};

export default Todolist;